<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/25
 * Time: 3:20 PM
 */
namespace app\backend\modules\common\controllers;

use app\backend\controllers\BaseController;
use app\backend\modules\common\services\UploadService;
use app\common\facades\Setting;
use app\common\models\CoreAttach;


class UploadController extends BaseController
{
    public function upload()
    {
        $file = request()->file('file');

        $type = request()->upload_type;

        $res = (new UploadService())->upload($file,$type);

        return $this->successJson('上传成功', $res);
    }
    public function getImageList()
    {
        if (request()->year != '不限') {
            $search['year'] = request()->year;
        }

        if(request()->month != '不限') {
            $search['month'] = request()->month;
        }
        $search['type'] = CoreAttach::IMAGE_TYPE;
        $attachList = CoreAttach::site()->search($search)
            ->orderby('created_at', 'desc')
            ->paginate(15);
        foreach ($attachList as $v) {
            $v->url = fmt_media_url($v['attachment']);
        }
        return $this->successJson('',$attachList);
    }
    public function delete()
    {
        $uid = \YunCms::$adminUid;
        $id = intval(request()->id);
        if (!is_array($id)) {
            $id = array(intval($id));
        }
        $remote = Setting::get('cms.remote_attach');
        $model = CoreAttach::site()->where('id', $id)
            ->where('uid', $uid);
        $coreAttach = $model->first();
        if ($coreAttach['upload_type']) {
            $status = file_remote_delete($coreAttach['attachment'],$remote);
        } else {
            $status = file_delete($coreAttach['attachment']);
        }
        if ($model->delete()) {
            return $this->successJson('删除成功');
        } else {
            return $this->errorJson('删除数据表数据失败');
        }

    }

    /**
     * 前端TinyMce编辑器保存文件
     * @return false|string
     * @throws \OSS\Core\OssException
     * @throws \app\common\exceptions\BizException
     */
    public function uploadTinyMce()
    {
        $file = request()->file('file');

        $type = request()->upload_type;

        $res = (new UploadService())->upload($file,$type,false);
        response()->json(['location' => $res['url']], 200, ['charset' => 'utf-8'])->send();
        exit();
    }
}